package com.jht.bletool.ui;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.github.rahatarmanahmed.cpv.CircularProgressView;
import com.google.android.material.tabs.TabLayout;
import com.hjq.permissions.XXPermissions;
import com.hjq.xtoast.OnClickListener;
import com.hjq.xtoast.XToast;
import com.jht.bletool.APP;
import com.jht.bletool.R;
import com.jht.bletool.adapter.ExpandableRecordDataAdapter;
import com.jht.bletool.adapter.MyViewPageAdapter2;
import com.jht.bletool.config.AppConfig;
import com.jht.bletool.fragment.BLEServiceFragment;
import com.jht.bletool.fragment.BleLogFragment;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DataTransmissionActivity extends BaseActivity implements ExpandableRecordDataAdapter.Callback {

    private static final String TAG = "DataTransmission";
    private TabLayout mTabLayout2;
    private ViewPager mVpDataTransmission;
    private ImageView mIvMenu;
    private TextView mTvTitle;
    private CircularProgressView mProgressView;
    private ImageView mIvClearLog;
    private ImageView mIvRecordData;
    private ImageView mIvQuestion;


    private BluetoothDevice ble_device;
    private BLEServiceFragment bleServiceFragment;
    private BleLogFragment bleLogFragment;
    private XToast show;
    private XToast showClear_log;
    private XToast execRecord_data;
    private String scan_record;

    public String getScan_record(){
        return scan_record;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_transmission);
        Intent intent = getIntent();
        if (intent != null) {
            Log.i(TAG, "onCreate: device ==> " + ((BluetoothDevice) (intent.getParcelableExtra("ble_device"))).getName());
            ble_device = (BluetoothDevice) (intent.getParcelableExtra("ble_device"));
            scan_record = (String) (intent.getStringExtra("scan_record"));
            Log.i(TAG, "onCreate:scan_record==>  " + scan_record);
        }
        initView();
        mTvTitle.setText(ble_device.getName());

        if (ble_device != null) {
            //启动ble service

        } else {
            Log.e(TAG, "ble_device is null!!");
        }
    }

    private void initView() {
        mIvMenu = findViewById(R.id.iv_menu);
        mIvMenu.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_action_left_arrow));
        mIvMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(bleServiceFragment != null){
                    bleServiceFragment.clear();
                }
                finish();
            }
        });
        mTvTitle = findViewById(R.id.tv_title);
        mProgressView = findViewById(R.id.progress_view);
        mProgressView.setVisibility(View.GONE);
        mIvQuestion = findViewById(R.id.iv_question);
        mIvQuestion.setVisibility(View.VISIBLE);
        mIvQuestion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //显示 FTMS 控制点 的操作码 以及参数
                showControlOPCodeDialog();
            }
        });

        mIvRecordData = findViewById(R.id.iv_record_data);
        mIvRecordData.setVisibility(View.VISIBLE);
        mIvRecordData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //显示操作数据记录
                showExecRecordData();

            }
        });

        mIvClearLog = findViewById(R.id.iv_clear_log);
        mIvClearLog.setVisibility(View.VISIBLE);
        mIvClearLog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //显示是否删除所有日志
                showClearAllLog();
            }
        });

        mTabLayout2 = findViewById(R.id.tab_layout_2);
        mVpDataTransmission = findViewById(R.id.vp_data_transmission);

        mVpDataTransmission.setOffscreenPageLimit(2);
        initViewPage();
        mTabLayout2.setupWithViewPager(mVpDataTransmission);

    }

    private void initViewPage() {
        List<Fragment> fragments = initFragments();
        MyViewPageAdapter2 myViewPageAdapter = new MyViewPageAdapter2(getSupportFragmentManager(), fragments);
        mVpDataTransmission.setAdapter(myViewPageAdapter);
    }

    private List<Fragment> initFragments() {
        bleLogFragment = BleLogFragment.newInstance(ble_device);
        bleServiceFragment = BLEServiceFragment.newInstance(ble_device);
        List<Fragment> data = new ArrayList<>();
        data.add(bleServiceFragment);
        data.add(bleLogFragment);
        return data;
    }

    @Override
    public void onBackPressed() {
        Log.e(TAG, "onBackPressed: showExecRecordDialog => " + showExecRecordDialog);
        if(showExecRecordDialog){
            execRecord_data.cancel();
            showExecRecordDialog = false;
            return;
        }
        if(bleServiceFragment != null){
            bleServiceFragment.clear();
        }
        super.onBackPressed();
    }

    private void showControlOPCodeDialog(){
        initControlInfoDialog();
    }
    private boolean showExecRecordDialog = false;
    private void showExecRecordData(){
        execRecord_data = new XToast(DataTransmissionActivity.this)
                .setView(R.layout.dialog_exec_record_data)
                .setDuration(0)
                // 设置动画样式
                .setAnimStyle(R.style.go_setting_anim_style)
                .setOnClickListener(R.id.ll_exec_parent_new, new OnClickListener<LinearLayout>() {
                    @Override
                    public void onClick(XToast toast, LinearLayout view) {
                        // 点击这个 View 后消失
                        showExecRecordDialog = false;
                        toast.cancel();
                    }
                });
        ExpandableListView expandableListView = (ExpandableListView)execRecord_data.findViewById(R.id.elv_all_record_data);
        initRecordExpandableListView(expandableListView);
        showExecRecordDialog = true;
        execRecord_data.show();
    }
    private ExpandableRecordDataAdapter expandableRecordDataAdapter = null;

    private void initRecordExpandableListView(ExpandableListView expandableListView) {
        /**
         * 1.准备group数组
         * 2.准备group对应的child数组
         */
        List<String> character = new ArrayList<>();
        Map<String,List<String>> character_map_recordData = new HashMap<>();
        SharedPreferences record_data = APP.getAppContext().getSharedPreferences(AppConfig.record_data, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = record_data.edit();
        Map<String, ?> all = record_data.getAll();
        for(Map.Entry<String, ?> entry:all.entrySet()){
            Log.d(TAG, "initRecordExpandableListView: key=> " + entry.getKey()+"|| value ==>" + entry.getValue());
            character.add(entry.getKey());
            String[] split = ((String) entry.getValue()).split(";");
            ArrayList<String> strings = new ArrayList<>();
            boolean b = Collections.addAll(strings, split);
            character_map_recordData.put(entry.getKey(),strings);
        }
        expandableRecordDataAdapter = new ExpandableRecordDataAdapter(this, character, character_map_recordData);
        expandableRecordDataAdapter.setCallback(this);
        expandableListView.setAdapter(expandableRecordDataAdapter);
    }

    private void showClearAllLog(){
        showClear_log = new XToast(DataTransmissionActivity.this)
                .setView(R.layout.dialog_clear_all_log)
                .setDuration(0)
                // 设置动画样式
                .setAnimStyle(R.style.go_setting_anim_style)
                .setOnClickListener(R.id.btn_close_log_dialog, new OnClickListener<Button>() {

                    @Override
                    public void onClick(XToast toast, Button view) {
                        // 点击这个 View 后消失
                        toast.cancel();
                        // 跳转到某个Activity
                        // toast.startActivity(intent);
                    }
                }).setOnClickListener(R.id.btn_confirm_clear_log, new OnClickListener<Button>() {
                    @Override
                    public void onClick(XToast toast, Button view) {
                        //清除所有日志
                        if(bleLogFragment != null){
                            bleLogFragment.clearAllLog();
                        }
                        toast.cancel();
                    }
                });

        showClear_log.show();
    }

    private void initControlInfoDialog() {
        String opcode = " Fitness Machine Control Point op code : \n"
                + "Op Code : Definition : Parameter"
                + "\n 0x00 : Request Control : N/A"
                + "\n 0x01 : Reset : N/A"
                + "\n 0x02 : Set Target Speed : UINT16"
                + "\n 0x03 : Set Inclination  : SINT16"
                + "\n 0x04 : Set Resistance Level : UINT8"
                + "\n 0x05 : Set Target Power : SINT16"
                + "\n 0x06 : Set Heart Rate : UINT8"
                + "\n 0x07 : Start or Resume : N/A"
                + "\n 0x08 : Stop or Pause : stop-01,pause-02"
                + "\n 0x09 : Set Expended Energy : UINT16"
                + "\n 0x0a : Set Number of Steps : UINT16"
                + "\n 0x0b : Set Number of Strides : UINT16"
                + "\n 0x0c : Set Distance :UINT24"
                + "\n 0x0d : Set Training Time : UINT16"
                + "\n 0x0e : Set Two HeartRate Zones : Array"
                + "\n 0x0f : Set Three HeartRate Zones: Array"
                + "\n 0x10 : Set Five HeartRate Zones : Array"
                + "\n 0x11 : Set IndoorBike Simulation: Array"
                + "\n 0x12 : Set Wheel Circumference: UINT16"
                + "\n 0x13 : Spin Down Control : start-01,ignore-02 "
                + "\n 0x14 : Set Cadence : UINT16"
                + "\n 1: change bt name，2：set Resistance"
                ;
        // 传入 Application 对象表示设置成全局的
        show = new XToast(DataTransmissionActivity.this)
                .setView(R.layout.layout_show_control_point_dialog)
                .setDuration(0)
                // 设置动画样式
                .setAnimStyle(R.style.go_setting_anim_style)
                .setOnClickListener(R.id.btn_close_dialog, new OnClickListener<Button>() {

                    @Override
                    public void onClick(XToast toast, Button view) {
                        // 点击这个 View 后消失
                        toast.cancel();
                        // 跳转到某个Activity
                        // toast.startActivity(intent);
                    }
                });
        ((TextView)(show.findViewById(R.id.tv_op_message))).setText(opcode);
        show.show();
    }

    @Override
    public void groupDataExec(String groupUUID,Map<String,List<String>> allData) {

    }

    @Override
    public void groupDataDel(String groupUUID,Map<String,List<String>> allData) {

    }

    @Override
    public void childDataExec(String groupUUID,String childCommData) {
        bleServiceFragment.sendChildRecordData(groupUUID,childCommData);
        Log.e(TAG, "childDataExec: ");
    }

    @Override
    public void childDataDel(String groupUUID,String childCommData) {

    }
}